var htmldomid = "";

$(document).ready(function(){
    editWindowHeight();

    var firstdom = $(".edit-htmldom")[0];
    renderEdit(firstdom.id);
    $("#edit_right_img").show();

    $(document).on("click",'.edit-htmldom',function(){
        $(".edit-htmldom").removeClass("htmldom-activity");
        $(".site-button-top").removeClass("htmldom-activity");
        $(".site-button-bottom").removeClass("htmldom-activity");
        var id =  $(this).attr("id");
        renderEdit(id);
    });

    $(document).on("click",'.site-button-top',function(){
        $(".edit-htmldom").removeClass("htmldom-activity");
        $(".site-button-top").removeClass("htmldom-activity");
        $(".site-button-bottom").removeClass("htmldom-activity");
        var id =  $(this).attr("id");
        renderEdit(id);
    });

    $(document).on("click",'.site-button-bottom',function(){
        $(".edit-htmldom").removeClass("htmldom-activity");
        $(".site-button-top").removeClass("htmldom-activity");
        $(".site-button-bottom").removeClass("htmldom-activity");
        var id =  $(this).attr("id");
        renderEdit(id);
    });

    $("#domlistsleft li").click(function(){
        $(".domlists-right ul").hide();
        $("#domlistsleft li").removeClass("active");
        var type =  $(this).attr("type");
        $(this).addClass("active");
        $("#edit_left_"+type).show();
    });

    $("#button_background_color").spectrum({
        color: "#0F80FF",
        cancelText: "取消",
        chooseText: "确定选择",
    });

    $("#button_color").spectrum({
        color: "#FFFFFF",
        cancelText: "取消",
        chooseText: "确定选择",
    });
});

$(window).resize( function  () {
    editWindowHeight();
});

function editWindowHeight() {
    var windowheight = $(window).height()-75;
    $(".edit-cotainer").css("height",windowheight+"px");
}

function previewSite(links_id,created_at) {
    $("#qrcodepreview").html("");
    var previewUrl = "http://ga.shiganyi.cn/pages/"+created_at+"/"+links_id+".html"
    var qrcode = new QRCode(document.getElementById("qrcodepreview"), {
        text: previewUrl,
        width: 120,
        height: 120,
        colorDark : "#000000",
        colorLight : "#ffffff",
        correctLevel : QRCode.CorrectLevel.H
    });
    $('#qrcodePreviewModal').modal('show');
}

function renderEdit(id) {
    htmldomid = id;
    var platfrom =  $("#"+id).attr("platfrom");
    var platfrom_detial =  $("#"+id).attr("platfrom_detial");
    $("#"+id).addClass("htmldom-activity");
    $(".edit-right-from").hide();
    editRightTitle(platfrom);
    if (platfrom == "img") {
        $("#edit_right_img").show();
        var imgsrc = $("#"+id+" img").attr("src");
        $("#image_show").attr("src",imgsrc).show();
        $("#img_url").val("");
        var atag = $("#"+htmldomid).children("a");
        if (atag.length >= 1) {
            var imglink = $("#"+id+" a").attr("href");
            $("#img_url").val(imglink);
        } else {
            $("#img_url").val("");
        }
    } else if (platfrom == "button") {
        if(platfrom_detial == "button_img" || platfrom_detial == "button_top_img" || platfrom_detial == "button_bottom_img"){
            $("#button_image_row").show();
            $("#button_animation_row").hide();
            $("#button_color_row").hide();
            var imgsrc = $("#"+id+" img").attr("src");
            $("#button_image_show").attr("src",imgsrc).show();
        } else {
            $("#button_image_row").hide();
            $("#button_animation_row").show();
            $("#button_color_row").show();
        }
        $("#edit_right_button").show();
        var btnclass = $("#"+id+" a").attr("class");
        var btncolor = $("#"+id+" a").css("color");
        var btnbackcolor = $("#"+id+" a").css("background-color");
        if (btnclass.indexOf("miniapp-btn") != -1) {
            $("#"+id+" a").attr("href","");
            $("#button_type_miniapp").addClass("active");
            $("#button_type_url").removeClass("active");
            $("#button_url").hide();
            $("#button_url_input").val("");
        } else {
            var buttonurl = $("#"+id+" a").attr("href");
            $("#button_url_input").val(buttonurl);
            $("#button_type_miniapp").removeClass("active");
            $("#button_type_url").addClass("active");
            $("#button_url").show();
        }
        $("#button_background_color").spectrum("set", btnbackcolor);
        $("#button_color").spectrum("set", btncolor);
    } else {
        $("#edit_right_text").show();
    }
}

function buttonAnimation(value) {
    $("#animation_type li").removeClass("active");
    $("#animation_type_"+value).addClass("active");
    var atag = $("#"+htmldomid).children("a");
    $("#button_"+value).show();
    var classes = "";
    if (value == "fullbeat") {
        classes = "site-button-fullbeat";
    } else if(value == "textbeat"){
        classes = "site-button-textbeat";
    } else {
        classes = "";
    }
    if (atag.length >= 1) {
        var childrenClass = $("#"+htmldomid+" a").attr("class");
        childrenClass = childrenClass.replace('site-button-fullbeat', '').replace('site-button-textbeat', '');
        $("#"+htmldomid+" a").attr("class",childrenClass + " "+classes);
    } else {
        var childrenClass = $("#"+htmldomid+" div").attr("class");
        childrenClass = childrenClass.replace('site-button-fullbeat', '').replace('site-button-textbeat', '');
        $("#"+htmldomid+" div").attr("class",childrenClass + " "+classes);
    }
}

function editRightTitle(platfrom) {
    if (platfrom == "button") {
        $("#edit_right_title").text("按钮组件");
        $("#edit_right_des").text("可以使用图片按钮定义更多样式");
    } else {
        $("#edit_right_title").text("图片组件");
        $("#edit_right_des").text("如果是长图,请将图片切成多段上传。");
    }
}

function renderEditAdd(platfrom,platfrom_detial) {
    var id = getRandomString(32);
    $(".edit-htmldom").removeClass("htmldom-activity");
    $(".edit-right-from").hide();
    var site_id = $("#site_id").val();
    editRightTitle(platfrom);
    if (platfrom == "img") {
        $("#edit_right_img").show();
        $("#img_url").val("");
        $("#"+htmldomid).after('<div class="edit-htmldom" id="'+id+'" platfrom="img"><img src="https://p6-orange.byteorge.com/img/ad-tetris-site/f59c53720312352885ae5df5051d032f.png~q75.awebp" class="site-img-12"></div>');       
    } else if (platfrom == "button") {
        $("#edit_right_button").show();
        $("#button_url_input").val("");
        if(platfrom_detial == "button_top_small" || platfrom_detial == "button_top_full" || platfrom_detial == "button_top_img"){
            $(".site-button-top").remove();
            if(platfrom_detial == "button_top_small"){
                $(".htmldom-cotainer").prepend('<div id="'+id+'" platfrom="'+platfrom+'" platfrom_detial="'+platfrom_detial+'" class="site-button-top"><a href="" class="site-button-default-circle miniapp-btn">顶部固定按钮</a></div>');
            } else if(platfrom_detial == "button_top_full") {
                $(".htmldom-cotainer").prepend('<div id="'+id+'" platfrom="'+platfrom+'" platfrom_detial="'+platfrom_detial+'" class="site-button-top"><a href="" class="site-button-default miniapp-btn">顶部固定按钮</a></div>');
            } else {
                $(".htmldom-cotainer").prepend('<div id="'+id+'" platfrom="'+platfrom+'" platfrom_detial="'+platfrom_detial+'" class="site-button-top"><a href="" class="miniapp-btn"><img src="https://p6-orange.byteorge.com/img/ad-tetris-site/file/1551790136895/72aa31c3f84fe1b9827ec489f76d5762~q75.awebp" class="site-img-12"></a></div>');
            }
        } else if(platfrom_detial == "button_bottom_small" || platfrom_detial == "button_bottom_full" || platfrom_detial == "button_bottom_img"){
            $(".site-button-bottom").remove();
            if(platfrom_detial == "button_bottom_small"){
                $(".htmldom-cotainer").append('<div id="'+id+'" platfrom="'+platfrom+'" platfrom_detial="'+platfrom_detial+'" class="site-button-bottom"><a href="" class="site-button-default-circle miniapp-btn">底部固定按钮</a></div>');
            } else if(platfrom_detial == "button_bottom_full") {
                $(".htmldom-cotainer").append('<div id="'+id+'" platfrom="'+platfrom+'" platfrom_detial="'+platfrom_detial+'" class="site-button-bottom"><a href="" class="site-button-default miniapp-btn">底部固定按钮</a></div>');
            } else {
                $(".htmldom-cotainer").append('<div id="'+id+'" platfrom="'+platfrom+'" platfrom_detial="'+platfrom_detial+'" class="site-button-bottom"><a href="" class="miniapp-btn"><img src="https://p6-orange.byteorge.com/img/ad-tetris-site/file/1551790136895/72aa31c3f84fe1b9827ec489f76d5762~q75.awebp" class="site-img-12"></a></div>');
            }
        } else {
            var button_html = "";
            if(platfrom_detial == "button_small"){
                button_html = '<a class="site-button-default-circle miniapp-btn" style="color:#FFFFFF;">按钮</a>';
            } else if(platfrom_detial == "button_full") {
                button_html = '<a class="site-button-default miniapp-btn" style="color:#FFFFFF;">按钮</a>';
            } else {
                button_html = '<a href="" class="miniapp-btn"><img src="https://p6-orange.byteorge.com/img/ad-tetris-site/file/1551790136895/72aa31c3f84fe1b9827ec489f76d5762~q75.awebp" class="site-img-12"></a>';
            }
            $("#"+htmldomid).after('<div class="edit-htmldom" id="'+id+'" platfrom="'+platfrom+'" platfrom_detial="'+platfrom_detial+'">'+button_html+'</div>');
            $("#edit_right_button").show();
        }
    }
    htmldomid = id;
    $("#"+id).addClass("htmldom-activity");
    renderEdit(id,platfrom);
}

function buttonTypeRender(buttontype) {
    $("#button_type li").removeClass("active");
    $("#button_type_"+buttontype).addClass("active");
    $("#button_url").hide();
    $("#button_miniapp").hide();
    $("#button_showFrom").hide();
    $("#button_"+buttontype).show();
    if (buttontype == "miniapp") {
        var atag = $("#"+htmldomid).children("a");
        $("#"+htmldomid+" a").addClass("miniapp-btn")
    } else {
        $("#"+htmldomid+" a").removeClass("miniapp-btn")
    }
}

function jsUploadCallBack(id,src) {
    $("#"+htmldomid+" img").attr("src",src);
}

function imgUrlChange(object) {
    var id = object.id;
    var url = $("#"+id).val();
    if (url != "") {
        if (url.indexOf("://") < 0) {
            mviewToastr("error","链接错误,请输入正确的http链接和urlscheme!");
            $("#"+id).val("");
            return;
        }
        if (url.indexOf("/pages/") >= 0 || url.indexOf("/l/") >= 0) {
            mviewToastr("error","您无需输入天天外链的外链地址!");
            $("#"+id).val("");
            return;
        }
    }
    if (id == "button_url_input") {
        var atag = $("#"+htmldomid).children("a");
        if (atag.length >= 1) {
            var childrenClass = $("#"+htmldomid+" a").attr("class");
            var childrenStyle = $("#"+htmldomid+" a").attr("style");
            var childrentext = $("#"+htmldomid+" a").text();
        } else {
            var childrenClass = $("#"+htmldomid+" div").attr("class");
            var childrenStyle = $("#"+htmldomid+" div").attr("style");
            var childrentext = $("#"+htmldomid+" div").text();
        }
        $("#"+htmldomid).html('<a href="'+url+'" target="_blank" class="'+childrenClass+'" style="'+childrenStyle+'">'+childrentext+'</a>');
    } else {
        var imgsrc = $("#"+htmldomid+" img").attr("src");
        if (url != "") {
            $("#"+htmldomid).html('<a href="'+url+'" target="_blank"><img src="'+imgsrc+'" class="site-img-12"></a>');
        } else {
            $("#"+htmldomid).html('<img src="'+imgsrc+'" class="site-img-12">');
        }
    }
}

function colorChange(object) {
    var id = object.id;
    var color = $("#"+id).val();
    if (id == "button_background_color") {
        $("#"+htmldomid+" a").css("background-color",color);
    } else if (id == "button_color") {
        $("#"+htmldomid+" a").css("color",color);
    }
}

function showFrmoCountDownShow(){
    var countDownShow = $("#showFrmoCountDownShow").is(":checked");
    if (countDownShow) {
        $("#showFrmoCountDownShowRow").show();
        $(".top-notice").css("display","block");
        $("#"+htmldomid).attr("onclick","showFrom(true);");
    } else {
        $("#showFrmoCountDownShowRow").hide();
        $(".top-notice").css("display","none");
        $("#"+htmldomid).attr("onclick","showFrom(false);");
    }
}

function showFrmoSendCode(){
    var showFrmoSendCode = $("#showFrmoSendCode").val();
    if (showFrmoSendCode == 2) {
        $(".site-from-one-code").css("display","none").attr("val","2");
    } else {
        $(".site-from-one-code").css("display","block").attr("val","1");
    }
}

function showFrmoButton(){
    var showFrmoButton = $("#showFrmoButton").val();
    $(".site-from-one-button").text(showFrmoButton);
}

function showFrmoNotice() {
    var showFrmoNotice = $("#showFrmoNotice").val();
    $(".top-notice span").text(showFrmoNotice+":");
}

function showFrmoTime() {
    var showFrmoTime = $("#showFrmoTime").val();
    $(".top-notice font").text(showFrmoTime+"S");
}

// 文字字体设计
function tetxFontName() {
    var tetxFontName = $("#tetxFontName").val();
    if(tetxFontName == "1"){
        document.execCommand('fontName', false, '');
    } else {
        document.execCommand('fontName', false, 'Source Han Sans');
    }
}

// 文字对齐方式
function tetxAlignment(aligntype) {
    if(aligntype == "left"){
        document.execCommand('justifyLeft', 'false', null );
    } else if (aligntype == "center") {
        document.execCommand('justifyCenter', 'false', null );
    } else {
        document.execCommand('justifyRight', 'false', null );
    }
}

// 文字大小
function tetxFontSize(type) {
    var fontsize = parseInt($("#tetxFontSize").val());
    if (type == "inc") {
        fontsize += 1;
    } else {
        fontsize -= 1;
    }
    $("#tetxFontSize").val(fontsize);
    // let parent = document.execCommand();
    var selection = document.getSelection()
    // 设置最后光标对象
    lastEditRange = selection.getRangeAt(0);
    //选中区域的Element元素
    var elem = lastEditRange.commonAncestorContainer;
    if(elem.nodeType != 1){
        elem = elem.parentNode;
    }
    var lineheight = (fontsize*1.5).toFixed(0);
    $("#tetxLineHeight").val(lineheight);
    elem.style.fontSize = fontsize+"px";
    elem.style.height = lineheight+"px";
    elem.style.lineHeight = lineheight+"px";
}

// 行高
function tetxLineHeight(type) {
    var lineheight = parseInt($("#tetxLineHeight").val());
    if (type == "inc") {
        lineheight += 1;
    } else {
        lineheight -= 1;
    }
    $("#tetxLineHeight").val(lineheight);
    var selection = document.getSelection()
    // 设置最后光标对象
    lastEditRange = selection.getRangeAt(0);
    //选中区域的Element元素
    var elem = lastEditRange.commonAncestorContainer;
    if(elem.nodeType != 1){
        elem = elem.parentNode;
    }
    elem.style.height = lineheight+"px";
    elem.style.lineHeight = lineheight+"px";
}

function getRandomString(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = $chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function deleteHtmlDom() {
    var nexthtmldomid = $("#"+htmldomid).next().attr("id");
    $("#"+htmldomid).remove();
    try {
        renderEdit(nexthtmldomid);
    } catch(err){
    }
    var htmldomNumber = $(".edit-htmldom").length;

    if (htmldomNumber <= 0) {
        $(".htmldom-cotainer").html('<div class="edit-htmldom" id="YY76ERh23nRrHAzHc53w6NjfayXNc7T6" platfrom="img"><img src="https://nilife.oss-cn-beijing.aliyuncs.com/miniapp/links/20221124/2a170017a9ba9eafe39b2cea02d79e8c.jpg" class="site-img-12"></div>');
        renderEdit("YY76ERh23nRrHAzHc53w6NjfayXNc7T6");
    }
}

function jsUpload(id,maxsize,callback=false) {
    var images = $("#upload_"+id).val();
    $(".images-border font").text("上传中...");
    var $file = event.currentTarget;
    lrz($file.files[0],{width: 800,quality:0.7,fieldName:'images'})
    .then(function (rst) {
        // getScaleSize($file,rst);
        var resultSize = (rst.fileLen/1024).toFixed(0);
        if (resultSize > maxsize) {
            mviewToastr("error","图片压缩后不能超过"+maxsize+"KB,当前为"+resultSize+"KB。");
            $("#upload_"+id).val('');
            return;
        }
        // 额外添加参数
        rst.formData.append("fileLen", rst.fileLen);
        var users_id = $("#users_id").val();
        var links_id = $("#links_id").val();
        var sign = $("#sign").val();
        var token = $("#token").val();
        rst.formData.append("users_id", users_id);
        rst.formData.append("links_id", links_id);
        rst.formData.append("sign", sign);
        rst.formData.append("token", token);
        $.ajax({
            url: "/api/version/1/upload/base_upload",
            type: "POST",
            dataType: "json",
            data: rst.formData,
            contentType: false,
            processData: false,
            success:function(data){
                if (data.status == "success") {
                    $("#"+id+"_show").attr("src",data.url);
                    $("#"+id).val(data.url);
                    $(".images-border font").text("选择图片");
                    if (callback) {
                        jsUploadCallBack(id,data.url);
                    }
                } else {
                    if (data.code == 1002) {
                        mviewToastr("error",data.msg);
                        setTimeout(function (){
                            window.location.href="/admin/login?msg="+data.msg;
                        }, 3000);
                    } else {
                        mviewToastr("error",data.msg);
                    }
                }
            },
            error:function(err){
                mviewToastr("error","网络异常,请联系客服处理！");
            }
        })
    })
    .catch(function (err) {
        mviewToastr("error","网络异常,请联系客服处理！");
    });
}

function publishPublic(type) {
    var html = $(".htmldom-cotainer").html();
    var links_id = $("#links_id").val();
    var name = "保存到草稿";
    if (type == "online") name = "发布落地页";
    html = $.trim(html);
    if (html == '<div class="edit-htmldom htmldom-activity" id="YY76ERh23nRrHAzHc53w6NjfayXNc7T6" platfrom="img"><img src="https://nilife.oss-cn-beijing.aliyuncs.com/miniapp/links/20221124/2a170017a9ba9eafe39b2cea02d79e8c.jpg" class="site-img-12"></div>') {
        mviewToastr("error","您当前未修改页面配置，无法"+name);
        return;
    }
    $.ajax({
            url: "/admin/links_lists/links_lists_html_update/"+links_id,
            type: "POST",
            data: {
                "html":html,
                "links_id":links_id,
                "type":type,
            },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success:function(data){
                if (data.status == "success") {
                    mviewToastr("success",data.msg);
                } else {
                    mviewToastr("error",data.msg);
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                if (XMLHttpRequest.status == 419) {
                    mviewToastr("error","因长时间未提交已掉线，请刷新网页重新提交!");
                }
            }
        })
}